package kr.mybatis;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SessionManager {
	private SqlSessionFactoryBuilder builder = null;
	private SqlSessionFactory factory = null;
	protected Reader reader = null;
	protected SqlSession session = null;
	
	private String config = "kr/mybatis/config/mybatis-config.xml";
	
	public SessionManager(){
		setAll();
	}
	
	public SessionManager(String configPath){
		setConfig(configPath);
		setAll();
	}
	
	public void setAll(){
		setReader();
		setBuilder();
		setFactory();
		setSession();
	}
	
	public void setReader() {
		try {
			this.reader = Resources.getResourceAsReader(this.config);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void setBuilder() {
		this.builder = new SqlSessionFactoryBuilder();
	}

	public void setFactory() {
		this.factory = builder.build(this.reader);
	}
	
	public SqlSession getSession() {
		return session;
	}

	public void setSession() {
		this.session = this.factory.openSession();
	}

	public <T> T getMapper(Class<T> type){
		return this.session.getMapper(type);
	}
	
	public void commit(){
		this.session.commit();
	}
	
	public void rollback(){
		this.session.commit();
	}
	
	public void close(){
		this.session.close();
	}
	
	public void closeAll(){
		this.session.close();
		try {
			this.reader.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String getConfig() {
		return config;
	}

	public void setConfig(String config) {
		this.config = config;
	}
}
